﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HtmlAgilityPack;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Data;

namespace HTMLParser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HtmlDocument doc;
        private List<int> childNodesIndex;
        public MainWindow()
        {
            InitializeComponent();
            doc = null;
        }

        private void btnParse_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = "HTML|*.htm";
            bool? result = dlg.ShowDialog();
            if (result == true)
            {
                doc = new HtmlDocument();
                doc.Load(dlg.FileName);
                HtmlNode body = doc.DocumentNode.SelectSingleNode("//body");
                txtHtml.Text = doc.DocumentNode.InnerHtml;
                txtName.Text = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]/table[2]/tr[2]/td[1]/p[2]/span[2]").InnerText.Replace(@"&nbsp;", "");
                txtPatientID.Text = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]/table[2]/tr[2]/td[5]/p[1]/span[2]").InnerText.Replace(@"&nbsp;", "");
                txtVisitID.Text = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]/table[2]/tr[2]/td[5]/p[2]/span[2]").InnerText.Replace(@"&nbsp;", "");
                txtBasicInformation.Text = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]/p[5]").InnerText.Replace(@"&nbsp;", "");
                txtTime.Text = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]/p[4]/span[1]").InnerText.Replace(@"&nbsp;", " ");
                HtmlNode node = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]");
                foreach (HtmlNode n in node.ChildNodes.ToArray())
                {
                    if (n.Name == "#text")
                    {
                        n.Remove();
                    }
                }
                tvHtml.ItemsSource = HtmlTree.InitRoot(node);
                txtDoctor.Text = "";
                txtRecord.Text = "";
                cmbTime.Items.Clear();
                txtNodeCount.Text = node.ChildNodes.Count.ToString();
                childNodesIndex = new List<int>();
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    if (node.ChildNodes[i].Name == "p")
                    {
                        Regex regex = new Regex(@"(?<value>^\d\d\d\d-\d\d-\d\d(&nbsp;\d\d:\d\d)?)");
                        Match match = regex.Match(node.ChildNodes[i].InnerText);
                        if (match.Success)
                        {
                            cmbTime.Items.Add(match.Value.Replace(@"&nbsp;", " "));
                            childNodesIndex.Add(i);
                        }
                    }
                }
                sldTimeLine.Maximum = childNodesIndex.Count - 1;
                

                if (node.ChildNodes[0].ChildNodes.Count == 2)
                {
                    txtType.Text = node.ChildNodes[childNodesIndex[0]].ChildNodes[1].InnerText.Replace(@"&nbsp;", "").Replace("　", "").Replace(" ", "");
                }
                string buffer = null;
                for (int i = childNodesIndex[0] + 1; i < childNodesIndex[1] - 1; i++)
                {
                    buffer = buffer + node.ChildNodes[i].InnerText.Replace(@"&nbsp;", " ");
                }
                txtRecord.Text = buffer;
                txtDoctor.Text = node.ChildNodes[childNodesIndex[1] - 1].InnerText.Replace(@"&nbsp;", "").Replace(" ", "");
            }
            
        }

        private void tvHtml_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (doc != null)
            {
                if (tvHtml.SelectedItem != null)
                {
                    txtXPath.Text = ((HtmlTree)tvHtml.SelectedItem).Info.XPath.ToString();
                    txtInnerText.Text = ((HtmlTree)tvHtml.SelectedItem).Info.InnerText.Replace(@"&nbsp;", "");
                    txtNodeCount.Text = ((HtmlTree)tvHtml.SelectedItem).Info.ChildNodes.Count.ToString();
                }
            }
        }

        private void btnViaXPath_Click(object sender, RoutedEventArgs e)
        {
            if (doc != null)
            {
                try
                {
                    HtmlNode node = doc.DocumentNode.SelectSingleNode(txtXPath.Text);
                    txtInnerText.Text = node.InnerText.Replace(@"&nbsp;", "");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.StackTrace);
                    MessageBox.Show("Wrong XPath");
                }
            }
        }

        private void cmbTime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbTime.HasItems)
            {
                HtmlNode node = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]");
                txtRecord.Text = "";
                txtDoctor.Text = "";
                txtType.Text = "";
                if (node.ChildNodes[childNodesIndex[cmbTime.SelectedIndex]].ChildNodes.Count == 2)
                {
                    txtType.Text = node.ChildNodes[childNodesIndex[cmbTime.SelectedIndex]].ChildNodes[1].InnerText.Replace(@"&nbsp;", "").Replace("　", "").Replace(" ", "");
                }
                if (cmbTime.SelectedIndex != childNodesIndex.Count - 1)
                {
                    string buffer = null;
                    for (int i = childNodesIndex[cmbTime.SelectedIndex] + 1; i < childNodesIndex[cmbTime.SelectedIndex + 1] - 1; i++)
                    {
                        buffer = buffer + node.ChildNodes[i].InnerText.Replace(@"&nbsp;", " ");
                    }
                    txtRecord.Text = buffer;
                    txtDoctor.Text = node.ChildNodes[childNodesIndex[cmbTime.SelectedIndex + 1] - 1].InnerText.Replace(@"&nbsp;", "").Replace(" ", "");
                }
                else
                {
                    string buffer = null;
                    int endIndex = 0;
                    for (int i = node.ChildNodes.Count - 1; i > 0; i--)
                    {
                        if (node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "").Replace(" ", "").Replace("\r", "").Replace("\n", "") != "")
                        {
                            txtDoctor.Text = node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "").Replace(" ", "");
                            endIndex = i;
                            break;
                        }
                    }
                    for (int i = childNodesIndex[cmbTime.SelectedIndex] + 1; i < endIndex; i++)
                    {
                        buffer = buffer + node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "");
                    }
                    txtRecord.Text = buffer;
                }
            }
        }

        private void sldTimeLine_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (doc != null)
            {
                sldTimeLine.ToolTip = "第" + (sldTimeLine.Value + 1).ToString() + "天";
                HtmlNode node = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]");
                txtRecord.Text = "";
                txtDoctor.Text = "";
                txtType.Text = "";
                if (node.ChildNodes[childNodesIndex[(int)sldTimeLine.Value]].ChildNodes.Count == 2)
                {
                    txtType.Text = node.ChildNodes[childNodesIndex[(int)sldTimeLine.Value]].ChildNodes[1].InnerText.Replace(@"&nbsp;", "").Replace("　", "").Replace(" ", "");
                }
                if ((int)sldTimeLine.Value != childNodesIndex.Count - 1)
                {
                    string buffer = null;
                    for (int i = childNodesIndex[(int)sldTimeLine.Value] + 1; i < childNodesIndex[(int)sldTimeLine.Value + 1] - 1; i++)
                    {
                        buffer = buffer + node.ChildNodes[i].InnerText.Replace(@"&nbsp;", " ");
                    }
                    txtRecord.Text = buffer;
                    txtDoctor.Text = node.ChildNodes[childNodesIndex[(int)sldTimeLine.Value + 1] - 1].InnerText.Replace(@"&nbsp;", "").Replace(" ", "");
                }
                else
                {
                    string buffer = null;
                    int endIndex = 0;
                    for (int i = node.ChildNodes.Count - 1; i > 0; i--)
                    {
                        if (node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "").Replace(" ", "").Replace("\r", "").Replace("\n", "") != "")
                        {
                            txtDoctor.Text = node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "").Replace(" ", "");
                            endIndex = i;
                            break;
                        }
                    }
                    for (int i = childNodesIndex[(int)sldTimeLine.Value] + 1; i < endIndex; i++)
                    {
                        buffer = buffer + node.ChildNodes[i].InnerText.Replace(@"&nbsp;", "");
                    }
                    txtRecord.Text = buffer;
                }
            }
        }

        private void btnLoadHtml_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = "HTML|*.htm";
            bool? result = dlg.ShowDialog();
            if (result == true)
            {
                doc = new HtmlDocument();
                doc.Load(dlg.FileName);
                tvHtml.ItemsSource = HtmlTree.InitRoot(dlg.FileName);
            }
            wbs.Source = new Uri(dlg.FileName);
            txtHtml.Text = doc.DocumentNode.InnerHtml;
        }


    }

}
